package com.kaiwukj.android.ufamily.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.PayEvent;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
       /* if (api != null) {
            api.unregisterApp();
        }*/
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            // 根据返回码
            int code = resp.errCode;
            Log.d("onPayEventCallback", "onResp:" + code);
            switch (code) {
                case 0:
                    // 去本地确认支付结果
                    EventBus.getDefault().post(new PayEvent(PayEvent.SUCCESS, 0, "支付成功"));
                    finish();
                    break;
                case -2:
                    EventBus.getDefault().post(new PayEvent(PayEvent.CANCEL, 0, "支付已取消"));
                    finish();
                    break;
                default:
                    EventBus.getDefault().post(new PayEvent(PayEvent.FAILED, 0, "支付失败"));
                    finish();
                    break;
            }
        }
    }
}